package cn.flying.cloud.flow.audit.context;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import cn.flying.cloud.flow.annotation.TaskController;
import cn.flying.cloud.flow.audit.controller.BaseFlowAuditController;

/**
 * @author: admin
 * @date: 2025年06月21日 23:15
 * @version: 1.0
 */
@Component
public class FlowControllerContext implements ApplicationContextAware, DisposableBean {

    private final Map<String, BaseFlowAuditController> beanCache = new ConcurrentHashMap<>();

    private ApplicationContext applicationContext;

    public BaseFlowAuditController getBean(String beanName) {
        return beanCache.get(beanName);
    }

    /**
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

        Map<String, Object> beans = this.applicationContext.getBeansWithAnnotation(TaskController.class);
        beans.forEach((k, v) -> {
            beanCache.put(k, (BaseFlowAuditController) v);
        });
    }

    /**
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        beanCache.clear();
    }
}
